import React, { useEffect, useState } from 'react';
import { View, Text, ScrollView, Image } from '@tarojs/components';
import TitleBar from '@/src/components/titleBar';
import './index.less';
import store from '@/src/store';
import { AtSearchBar } from 'taro-ui';

interface City {
  areaCode: string;
  areaName: string;
  letter: string;
}

type CityData = Record<string, City[]>;

const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

const SelectCity: React.FC = () => {
  // 全部城市数据，按首字母分组
  const [cityData, setCityData] = useState<CityData>({});
  // 右侧点击后要滚动到的 id
  const [scrollId, setScrollId] = useState<string>('');
  // 当前定位城市
  const [currentCity, setCurrentCity] = useState('定位中...');
  // 搜索关键词（暂不做过滤）
  const [search, setSearch] = useState('');

  // 拉城市接口
  const fetchCities = async () => {};

  // 定位当前城市
  const locate = () => {
    // Taro.getLocation({ type: 'gcj02' })
    //   .then((loc) => {
    //     // 这里假设有接口能通过经纬度反查城市名
    //     return Taro.request<{ cityName: string }>({
    //       url: 'https://api.example.com/reverseGeocode',
    //       data: { lat: loc.latitude, lng: loc.longitude },
    //     });
    //   })
    //   .then((r) => setCurrentCity(r.data.cityName))
    //   .catch(() => setCurrentCity('定位失败'));
  };

  useEffect(() => {
    fetchCities();
    locate();
  }, []);

  return (
    <View
      className="select-city-page"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title="选择城市"></TitleBar>
      {/* 搜索框 */}
      <View className="search-bar">
        <AtSearchBar
          placeholder="搜索城市"
          className="custom-search-bar"
          value={search}
          showActionButton={true}
          actionName="取消"
          onChange={(val: string) => setSearch(val)}
        />
      </View>

      {/* 当前定位城市 + 重新定位 */}
      <View className="location-row">
        <Text className="location-city">当前定位城市</Text>
        <View className="locate-btn" onClick={locate}>
          <Image
            src="https://file.linkcook.cn/image/wineMiniProgram/imgs/nearby/location.png"
            className="locate-icon"
          />
          <Text>重新定位</Text>
        </View>
      </View>
      <View className="current-city">{currentCity}</View>

      {/* 内容区：左右两列 */}
      <View className="body">
        {/* 左：城市列表 */}
        <ScrollView
          className="city-list"
          scrollY
          scrollIntoView={scrollId}
          scrollWithAnimation
        >
          {LETTERS.map((letter) => {
            const list = cityData[letter] || [];
            if (list.length === 0) return null;
            return (
              <View key={letter} id={letter} className="group">
                <Text className="group-letter">{letter}</Text>
                {list.map((city) => (
                  <Text key={city.areaCode} className="city-name">
                    {city.areaName}
                  </Text>
                ))}
              </View>
            );
          })}
        </ScrollView>

        {/* 右：字母索引 */}
        <View className="letter-index">
          {LETTERS.map((letter) => (
            <Text
              key={letter}
              className="letter"
              onClick={() => setScrollId(letter)}
            >
              {letter}
            </Text>
          ))}
        </View>
      </View>
    </View>
  );
};

export default SelectCity;
